package wh.ispct
import grails.converters.*;

class FileItemController {
	String fileDir = "/upload"
	
	def upload() {
		def msg = ["err":""]
		def file = new FileItem()
		
		try{
			def uploadedFile = request.getFile("filedata")
			if(!uploadedFile.empty){
				println "Class: ${uploadedFile.class}"
				println "Name: ${uploadedFile.name}"
				println "OriginalFileName: ${uploadedFile.originalFilename}"
				println "Size: ${uploadedFile.size}"
				println "ContentType: ${uploadedFile.contentType}"
			}

			//新建一个Content file
			file.fileName = uploadedFile.originalFilename
			file.fileType = params.fileType
			file.createDate = new Date()
			println "validate:" + file.validate()
			println "errors:" + file.errors
			file.save()
			print "id:" + file.id
			println 'save file :'+ file.id + "," + file.fileName + ","  + file.createDate 

			//返回Id，写入文件
			def serverFile = servletContext.getRealPath("/") + fileDir + "/" + file.id
			println "save to : " +  serverFile
			uploadedFile.transferTo( new File( serverFile))
			msg["msg"] = "/inspector/fileItem/get/" + file.id
			msg["id"]  = file.id
			msg["fileName"] = file.fileName
			msg["createDate"] = file.createDate
		}catch(e){
			e.printStackTrace()
			//log.error(e)
			if(file.id){
				file.delete()
			}
			msg["error"] = e.message
			msg.put("msg", e.getMessage())
		}
		println msg.encodeAsJSON()
		render(text: msg.encodeAsJSON(), contentType: "text/html", encoding: "UTF-8")
	}
	
	def get(){
		FileItem file = FileItem.get(params.id)
		def uploadDir = servletContext.getRealPath("/") + fileDir + "/"
		log.info uploadDir
		def filepath = null
		if(file== null){
			filepath = uploadDir + "notfound.jpg"
		}else{
			response.setContentType("application/octet-stream")
			response.setHeader("Content-disposition", "attachment; filename=${file.fileName}")
			filepath = uploadDir + file.id
		}
		
		def out = response.outputStream
		def inputStream = new FileInputStream(filepath)
		byte[] buffer = new byte[1024]
		int i = -1
		while ((i = inputStream.read(buffer)) != -1) {
			out.write(buffer, 0, i)
		}
		inputStream.close()
	}
	
	def delete(){
		def msg = ["success":true]
		try{
			FileItem file = FileItem.get(params.id)
			if(file != null){
				file.delete()
			}
		}catch(e){
			msg.put("success", false)
			msg.put("msg", e.getMessage())
		}
		render  (contentType:"text/json"){
			msg
		}
	}
	
	def list(){
		def msg = ["success":true]
		try{
			def fileList = FileItem.findAllByContent(Content.get(params.contentId))
			msg["data"]= fileList 
		}catch(e){
			e.printStackTrace()
			msg.put("success", false)
			msg.put("msg", e.getMessage())
		}
		render  (contentType:"text/json"){
			msg
		}
	}
	
	def GetFileExt(String fullPath){
		if (fullPath)
			return fullPath.substring(fullPath.lastIndexOf('.') + 1);
		else 
			return "";
	}
}
